<template>
	<view class="mainbgc">
		<header-top :messageInfo="{typeFlag:true,message:'客户结算统计明细',liner:false}">
			<view class="rightmsg" slot="rightmsg">
				<view class="rightmsg_content flexleft" @click="startPrint">
					<view class="dayinji"></view>
				</view>
			</view>
		</header-top>
		<view class="mainpadding_top ffffff">
			<view class="header flexbetween">
				<view class="headerchild" style="flex: 0.7; ">单号</view>
				<view class="headerchild headercenter" style="flex: 1;">日期</view>
				<view class="headerchild headercenter" style="flex: 1;">结算单位</view>
				<view class="headerchild headercenter" style="flex: 0.7;">已付</view>
				<view class="headerchild headerright" style="flex: 0.7;">未付</view>
			</view>
			<view class="content_child " v-for="item in list.goods" :key="item.id">
				<view class="flexbetween">
					<view class="contentchild" style="flex: 0.7; ">{{item.purchase_code}}</view>
					<view class="contentchild headercenter" style="flex: 1;">{{item.purchase_time}}</view>
					<view class="contentchild headercenter" style="flex: 1;">{{item.customer}}</view>
					<view class="contentchild headercenter" style="flex: 0.7;">￥{{item.write_off || 0}}</view>
					<view class="contentchild miancolor headerright" style="flex: 0.7;">￥{{item.write_off_money}}</view>
				</view>

			</view>
		</view>
		<view class="mainpadding flexbetween">
			<view class="flexleft">
				<view class="contentchild margin_right">合计:</view>
				<view class="contentchild">{{list.statistical.customer_num}}个客户</view>
			</view>
			<view class="flexright">
				<view class="miancolor margin_right">已付{{list.statistical.yf_money}}元</view>
				<view class="miancolor" style="color: #ff0000;">未付{{list.statistical.wf_money}}元</view>
			</view>
		</view>
		<view class="mainpadding flexbetween">
			<view class="flexleft">
				<view class="contentchild">{{list.statistical.starttime}}--{{list.statistical.endtime}}</view>
			</view>
			<view class="flexright">
				<view class="miancolor">生成日期：{{datetime}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	const tsc = require("@/util/ble/tsc.js");
	const esc = require("@/util/ble/esc.js");
	const encode = require("@/util/ble/encoding.js");
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				datetime: this.date(Number(new Date())),
				arr: [],
				type: "", //1退货单，2采购单，3采购退货单，4入库单，5销售单
				list: {
					goods: [{
						collection_id: 1,
						customer: "kehu1",
						id: 4,
						purchase_code: "SK20221116001",
						purchase_time: "2022-11-16",
						write_off: 0,
						write_off_money: -48,
					}],
					statistical: {
						customer_num: 1,
						endtime: "2022-11-16",
						starttime: "2022-11-16",
						wf_money: -48,
						yf_money: 0,
					}
				},
				// 打印机技术参数
				dyjshow: false,
				dyj: 0, //0热敏,1针式
				sendContent: "../../../static/image/news/boy.png",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '../../static/img/abc_ic_star_black_16dp.png',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				// 打印机技术结束
			}
		},
		onLoad(options) {
			let data = JSON.parse(decodeURIComponent(options.data));
			this.arr = data.arr
			console.log(this.arr, '跳转页面接收参数')
			this.init()
			// 打印机
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// 打印机结束
		},
		// 打印机开始
		computed: mapState(['sysinfo', 'Bluetooth']),
		onReady() {
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
				list[j] = i;
				j++
			}
			for (let i = 1; i < 10; i++) {
				numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
		},
		// 打印机结束
		onShow() {
			// 打印机开始
			let that = this;
			let width;
			let height;
			uni.getImageInfo({
				src: that.imageSrc,
				success(res) {
					console.log(res.width)
					console.log(res.height)
					width = res.width
					height = res.height
					that.canvasWidth = res.width;
					that.canvasHeight = res.height;
				}
			})
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			// if (app.globalData.platform == "android") {
			//   ctx.translate(width, height)
			//   ctx.rotate(180 * Math.PI / 180)
			// }
			ctx.drawImage(this.imageSrc, 0, 0, width, height);
			ctx.draw();
			// 打印机结束
		},
		methods: {
			init() {
				httpRequest.request('appapi/manage/goods/jiesuan_detail', 'POST', {
					purchase_code: this.arr.join(),
				}, false, false, true).then(res => {
					this.list = res.data
				}).catch(err => {
					httpRequest.toast(err.msg);
				})
			},
			date(timer) {
				var date = new Date(timer); //当前时间
				var year = date.getFullYear() //返回指定日期的年份
				var month = repair(date.getMonth() + 1); //月
				var day = repair(date.getDate()); //日
				var curTime = year + "-" + month + "-" + day

				function repair(i) {
					if (i >= 0 && i <= 9) {
						return "0" + i;
					} else {
						return i;
					}
				}
				return curTime
			},
			// 开始打印
			startPrint() {
				this.dyjshow = true
			},
			dyjconfirm() {
				this.dyjshow = false
				if (this.dyj == 0) {
					this.receiptTest()
				} else {
					this.needlePrint()
				}
			},
			// 针式打印
			needlePrint() {
				// 直接调取打印接口数据就行
				httpRequest.request('appapi/manage/prints/statistical_printer', 'POST', {
					type: this.type || 1,
					staff_member_id: this.yuangong.id
				}, false, false, true).then(res => {
					httpRequest.toast(res.msg)
				}).catch(err => {
					// httpRequest.toast(err.msg);
				})
			},
			// 打印机开始
			receiptTest() {
				var that = this;
				var canvasWidth = that.canvasWidth
				var canvasHeight = that.canvasHeight
				var command = esc.jpPrinter.createNew()
				command.init()
				// 标题
				command.bold(1); //加粗
				command.setFontSize(16); //字体大小
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.rowSpace(100);
				command.setText("客户结算统计明细");
				command.setPrint();
				command.rowSpace(60); //行间距
				command.bold(0); //取消加粗
				command.setFontSize(0); //正常字体
				// 表格
				command.setSelectJustification(0) //居中0左对齐1居中对齐2右对齐
				command.rowSpace(80); //间距
				command.bold(5); //加粗
				command.setText("单号");
				command.setAbsolutePrintPosition(170);
				command.setText("结算单位");
				command.setAbsolutePrintPosition(350);
				command.setText("已付");
				command.setAbsolutePrintPosition(480);
				command.setText("未付");
				command.setPrint()
				command.bold(0); //加粗
				that.list.goods.forEach(item => {
					command.setText(item.purchase_code);
					command.setAbsolutePrintPosition(170);
					command.setText(item.customer);
					command.setAbsolutePrintPosition(350);
					command.setText("￥"+item.write_off || 0);
					command.setAbsolutePrintPosition(480);
					command.setText("￥"+item.write_off_money || 0);
					command.setPrint();
					command.setText("日期："+item.purchase_time);
					command.setPrint();
				})
				command.bold(5); //加粗
				command.setText("合计：");
				command.setText(that.list.statistical.customer_num + "个客户，");
				command.setText("已付："+that.list.statistical.yf_money);
				command.setText("，未付："+that.list.statistical.wf_money);
				command.setPrint()
				command.setText(that.list.statistical.starttime+"--"+that.list.statistical.endtime);
				command.setPrint()
				command.setText("生成日期："+that.datetime);
				command.setPrint()
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.setText("询博技术支持");
				command.setPrintAndFeedRow(3);
				that.isReceiptSend = true;
				that.prepareSend(command.getData());
			},
			//准备发送，根据每次发送字节数来处理分包数量
			prepareSend(buff) {
				console.log(buff);
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				console.log(looptime + "---" + lastData)
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = that.Bluetooth;
			
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log(res)
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {
						currentTime++
						if (currentTime <= loopTime) {
							that.currentTime = currentTime;
							that.Send(buff)
						} else {
							//  uni.showToast({
							// title: '已打印第' + currentPrint + '张',
							//  })
							if (currentPrint == printNum) {
								that.looptime = 0;
								that.lastData = 0;
								that.currentTime = 1;
								that.isReceiptSend = false;
								that.isLabelSend = false;
								that.currentPrint = 1;
							} else {
								currentPrint++;
								that.currentPrint = currentPrint;
								that.currentTime = 1;
								that.Send(buff)
							}
						}
					}
				})
			},
			
			// 打印机结束
		}
	}
</script>

<style>
	.dayinji {
		width: 40rpx;
		height: 40rpx;
		background-image: url("@/static/image/system/my2.png");
		background-size: 100% 100%;
	}

	.miancolor {
		color: #0BBDCB;
	}

	.totle {
		padding-bottom: 150rpx;
	}

	.margin_topx {
		margin-top: 10rpx;
	}

	.huisetext {
		font-size: 24rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.lansetext {
		font-size: 24rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #999999;
	}

	.center {
		padding: 0 40rpx;
		margin: 30rpx auto;
		background-color: #fff;
	}

	.foot {
		padding: 0 40rpx;
		margin: 0 auto;
	}

	.headercenter {
		text-align: center;
	}

	.headerchild {
		font-size: 32rpx;
		font-weight: bold;
	}

	.headerbottom {
		font-size: 28rpx;
		font-weight: bold;
	}

	.content {
		padding-top: 30rpx;
	}

	.contentchild {
		font-size: 26rpx;
		word-break: break-all;
	}

	.headerright {
		text-align: right;
	}

	.content_child {
		margin: 30rpx 0 0 0;
	}
</style>